package cl.ncx.cmvrc.util.serviceLocator;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ServiceLocator implements IServiceLocator{
	
	private static ServiceLocator serviceLocator;
	private Logger log = Logger.getLogger(ServiceLocator.class.getName());
	private Context ctx;
	public String url = null;
	
	/**
	 * Singleton
	 * @return
	 * @throws ServiceLocatorException
	 */
	public static synchronized ServiceLocator getInstance() throws ServiceLocatorException {
		if(serviceLocator == null){
			serviceLocator = new ServiceLocator();
		}
		return serviceLocator;
	}
	
	/**
	 * Constructor con inicializacion de contexto
	 * @throws ServiceLocatorException
	 */
	private ServiceLocator() throws ServiceLocatorException{
		try{
			ctx = getInitialContext();
		}catch (Exception e) {
			throw new ServiceLocatorException(e.getMessage());
		}
	}
	
	/**
	 * Metodo que permite hacer el lookup del componente a utilizar 
	 * Lookup
	 * @param name
	 * @return Object
	 * @throws ServiceLocatorException 
	 */
	public Object lookup(String FACADE_NAME)
			throws ServiceLocatorException {
		try{
			//System.out.println("eerr-ear/"+FACADE_NAME+"/remote");
			return ctx.lookup(FACADE_NAME);

		}catch (NamingException e) {
			e.printStackTrace();
			log.log(Level.SEVERE,"componente eerr-ear");
			throw new ServiceLocatorException(e);
		}
	}
	
	/**
	 * Metodo que permite iniciar el contexto parea luego hacer el lookup en el JNDI
	 * 
	 * @return Context
	 * @throws Exception
	 */
	private Context getInitialContext() throws Exception {

		try {
			
			return new InitialContext();
		}catch (Exception e) {
			log.log(Level.SEVERE,"Inicializar Contexto con url "+this.url);	
			throw e;
		}
	}

	public static void initServiceLocator() {
		serviceLocator = null;

	}
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Context getContext() {
		return ctx;
	}

}
